<?php
use Base\AdminController;
use Illuminate\Support\Str;
use WeChat\Exceptions\InvalidResponseException;
use WeChat\Exceptions\LocalCacheException;
use WeChat\User;

class WechatUserController extends AdminController
{
    protected string $table = 'wechat_users';

    protected string $model = "WechatUser";

    public function syncDataAction(): void
    {
        try {
            $config = Config::get("wechat");
            $user = new User([
                'appid' => $config['AppId'],
                'appsecret' => $config['AppSecret']
            ]);
            $data = $user->getUserList(Cache::get("wechat_next_openid")??"");
            $insert = [];
            if (!isset($data['errcode'])) {
                foreach ($data['data']['openid'] as $vo) {
                    $info = $user->getUserInfo($vo);
                    $info['tagid_list'] = $info['tagid_list']?json_encode($info['tagid_list']):'[]';
                    $info['uuid'] = (string)Str::uuid();
                    $info['subscribe_time'] = date("Y-m-d H:i:s",$info['subscribe_time']);
                    $info['created_at'] = date("Y-m-d H:i:s");
                    unset($info['city']);
                    unset($info['province']);
                    unset($info['country']);
                    $insert[] = $info;
                }
                Cache::set("wechat_next_openid",$data['next_openid']);
                WechatUserModel::upsert($insert,['openid']);
                $this->apiSuccess([],'同步成功',20000);
            }else {
                $this->apiError($data['errcode']."-".$data['errmsg']);
            }
        } catch (InvalidResponseException|LocalCacheException $e) {
            $this->apiError($e->getMessage());
        }
    }

    /**
     * 拉黑/取消拉黑
     * @return void
     */
    public function blackAction():void
    {
        try {
            $config = Config::get("wechat");
            $user = new User([
                'appid' => $config['AppId'],
                'appsecret' => $config['AppSecret']
            ]);
            $openid = WechatUserModel::query()
                ->where("id",Request::input("ids"))
                ->where("is_black",0)
                ->get();
            $openid_black =   WechatUserModel::query()
                ->where("id",Request::input("ids"))
                ->where("is_black",1)
                ->get();
            $data = $user->batchBlackList($openid->pluck("openid")->toArray());
            $data_black = $user->batchUnblackList($openid_black->pluck("openid")->toArray());
            if ($data['errcode']==0&&$data_black['errcode']==0) {
                WechatUserModel::where("id",$openid->pluck("id")->toArray())->update(['is_black'=>1]);
                WechatUserModel::where("id",$openid_black->pluck("id")->toArray())->update(['is_black'=>0]);
            }else {
                $this->apiError($data['errmsg'].$data_black['errmsg']);
            }
            $this->apiSuccess([],"操作成功",20000);
        }catch (Exception $exception) {
            Log::$customFileName = LOG_PATH."/errors/";
            Log::error($exception->getMessage().$exception->getTraceAsString());
			$this->apiError($exception->getMessage());
        }
    }

	public function remarkAction():void
	{
		try {
            $config = Config::get("wechat");
            $user = new User([
                'appid' => $config['AppId'],
                'appsecret' => $config['AppSecret']
            ]);
            $fans = WechatUserModel::query()
                ->where("id",Request::input("id"))
                ->first();
            $data = $user->updateMark($fans['openid'], Request::input("remark"));
            if ($data['errcode']==0) {
                WechatUserModel::where("id",$fans['id'])->update(['remark'=>Request::input("remark")]);
            }else {
                $this->apiError($data['errmsg'].$data['errmsg']);
            }
            $this->apiSuccess([],"操作成功",20000);
        }catch (Exception $exception) {
            Log::$customFileName = LOG_PATH."/errors/";
            Log::error($exception->getMessage().$exception->getTraceAsString());
			$this->apiError($exception->getMessage());
        }
	}

}
